import { login, getInfo, getUserDetailByid } from '@/api/user'
import { getToken, setToken, removeToken, setTimestamp } from '@/utils/auth'
import { resetRouter } from '@/router'
// import { Message } from 'element-ui'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, result) {
    state.userInfo = result
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // async login(context, data) {
  //   try {
  // 发请求
  //     const { data: { success, message, data: token }} = await login(data)
  //     if (success) {
  // 保存token
  //       context.commit('setToken', token)
  //     } else {
  // 200状态码
  //       Message.error(message)
  //     }
  //   } catch (error) {
  // 状态错误
  //     MessageChannel.error(error.message)
  //     console.log(error)
  //   }
  // }

  async login(context, data) {
  // 发请求
    const token = await login(data)
    // 保存token
    context.commit('setToken', token)
    // 保存时间戳
    setTimestamp()
  },
  async getUserInfo(context) {
    const result = await getInfo()
    const detail = await getUserDetailByid(result.userId)
    context.commit('setUserInfo', { ...result, ...detail })
    return result
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    // 重置路由配置
    resetRouter()
    // 重置VUEX路由数据
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

